<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>购票页面</title>
</head>
<body>
<h1>购票页面</h1>
<p th:if="${error}" style="color: red;">[[${error}]]</p>
<p th:if="${success}" style="color: green;">[[${success}]]</p>
<p>电影标题: <span th:text="${mtitle}"></span></p>
<p>价格: <span th:text="${movie.price}"></span></p>
<p>购票数量: <input type="number" id="count" name="count" min="1" value="1"></p>
<p>总价: <span id="totalPrice"></span></p>
<p>购票时间: <span th:text="${#dates.format(#dates.createNow(), 'yyyy-MM-dd HH:mm:ss')}"></span></p>

<form th:action="@{/buyTicket}" method="post">
    <input type="hidden" th:name="mid" th:value="${movie.mid}">
    <input type="hidden" th:name="username" th:value="${username}">
    <input type="hidden" id="totalPriceInput" name="totalPrice">
    <input type="hidden" id="countInput" name="count" value="1">
    <input type="submit" value="提交订单">
</form>

<a th:href="@{/movieInfo(mid=${movie.mid}, username=${username})}">返回电影详情</a>

<script>
    const price = parseFloat('[[${movie.price}]]');
    const countInput = document.getElementById('count');
    const totalPriceSpan = document.getElementById('totalPrice');
    const totalPriceInput = document.getElementById('totalPriceInput');
    const countHiddenInput = document.getElementById('countInput');

    function updateTotalPrice() {
        const count = parseInt(countInput.value);
        const totalPrice = price * count;
        totalPriceSpan.textContent = totalPrice.toFixed(2);
        totalPriceInput.value = totalPrice.toFixed(2);
        countHiddenInput.value = count;
    }

    countInput.addEventListener('input', updateTotalPrice);
    updateTotalPrice();

    // 检查是否有成功信息
    const successMessage = document.querySelector('p[style="color: green;"]');
    if (successMessage) {
        alert(successMessage.textContent);
        window.location.href = `[[@{/movieInfo(mid=${movie.mid}, username=${username})}]]`;
    }
</script>
</body>
</html>